package com.lucy.viewer.browser.provider;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.lucy.viewer.constant.ViewerServiceEnum;
import com.lucy.viewer.params.ViewerFile;
import com.lucy.viewer.service.ViewerFileService;
import com.lucy.viewer.service.ViewerService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Slf4j
@Service
@AllArgsConstructor
public class BrowserViewerServiceImpl implements ViewerService {
    ViewerFileService viewerFileService;


    @Override
    public ViewerServiceEnum service() {
        return ViewerServiceEnum.BROWSER;
    }

    @Override
    public ModelAndView loadPreviewView(String documentKey, HttpServletResponse response) throws IOException {
        ViewerFile viewerFile = viewerFileService.getViewerFile(documentKey);
        // 获取文件路径
        String filePath = viewerFile.getPath();
        // 获取流
        InputStream in = FileUtil.getInputStream(new File(filePath));

        String fileName = viewerFile.getFileName();
        // 转化 bytes
        byte[] buffer = FileCopyUtils.copyToByteArray(in);
        // 写入
        try{
            response.reset();
            OutputStream ops = new BufferedOutputStream(response.getOutputStream());
            response.setHeader(HttpHeaders.CONTENT_TYPE,viewerFileService.getContentType(FileNameUtil.extName(fileName)));
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=" + viewerFile.getFileName());
            ops.write(buffer);
            ops.flush();
            ops.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ModelAndView loadEditorView(String documentKey, HttpServletResponse response) throws IOException {
        return loadPreviewView(documentKey,response);
    }

    @Override
    public Object editorCallBack(Map<String, Object> map) {
        return null;
    }
}
